<?php
error_reporting(-1);
echo "Creating temporary zip archive...\n";
$zip = new ZipArchive();
$zip->open(dirname(__FILE__) . '/dist/pack.zip', ZipArchive::CREATE);

echo "Adding files...\n";
$root = dirname(__FILE__);
addDir("$root/src", $zip);

echo "Saving zip file...\n";
$zip->close();

echo "Creating installer...\n";
$installer = fopen($root . '/dist/index.php', 'wb');
$source = fopen($root . '/installer/index.php', 'rb');
while (!feof($source)) {
    $buffer = fread($source, 4096);
    fwrite($installer, $buffer);
}
fclose($source);

echo "Including zip archive...\n";
$buffer = file_get_contents("$root/dist/pack.zip");
fwrite($installer, base64_encode($buffer));
fclose($installer);

echo "Removing temporary zip archive...\n";
unlink($root . '/dist/pack.zip');
echo "Done. Installer is located in dist/index.php";

function addDir($dirName, ZipArchive $zip, $path = '') {
    $dir = opendir("$dirName$path");
    while ($file = readdir($dir)) {
        if (($file == '.') || ($file == '..')) {
            continue;
        }
        $local = preg_replace('@^/@', '', "$path/$file");
        echo "    adding $local\n";
        if (is_dir("$dirName$path/$file")) {
            $zip->addEmptyDir("$local");
            addDir($dirName, $zip, "$path/$file");
        } else {
            $zip->addFile("$dirName$path/$file", $local);
        }
    }
    closedir($dir);
}
?>